#include <cv.h>
#include <highgui.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <fstream>
#include <iostream>
#include <string.h>
#include <dirent.h>
#include <set>
#include <time.h>
#include <iostream>

#include "io/HMMBuilder.h"
#include "io/TrackLoader.h"
#include "model/HMM.h"
#include "model/MappedRecognizer.impl.h"

const char* baseDirDefault = "./base/";
const char* videoDirDefault = "../video/";

bool getdir (const char* dir, vector<string> &files) {
    DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(dir)) == NULL) {
        cout << "Error(" << 1 << ") opening " << dir << endl;
        return true;
    }

    while ((dirp = readdir(dp)) != NULL) {
        files.push_back(string(dirp->d_name));
    }
    closedir(dp);
    return false;
}

bool fileExists(const char *fname) {
  return access(fname, 0) != -1;
}

int main(int argc, const char** argv) {
	
	std::vector<std::string> files = vector<string>();
	getdir(baseDirDefault, files);
	
	// number of states
	const unsigned n = 5;
	// size of alphabet
	const unsigned m = 8;
	// max number of training iterations
	const unsigned maxIter = 100;
	// training delta
	const double delta = 0.001;
	// number of models
	double eps = 1.0e-10;
	
	std::vector<pair<std::string, HMM> > models;
	
	for (unsigned int i = 0; i < files.size(); i++) {
		if (files[i].size() >= 5 && files[i].substr(files[i].size() - 3) == "lrn") {
		    	std::cout << "add " << files[i] << "\n";
		    	std::string symbol = files[i].substr(0, files[i].size() - 4);
		    	std::cout << "symbol = " << symbol << "\n";
			HMM model;
			model.initLRB(n, m, 0.5);
		    	HMMBuilder::build((baseDirDefault + files[i]).c_str(), model);
			model.print();
			
			models.push_back(std::pair<std::string, HMM>(symbol, model));
		}
	}
	
	// Recognize
	for (unsigned int i = 0; i < files.size(); i++) {
		if (files[i].size() >= 5 && files[i].substr(files[i].size() - 3) == "lrn") {
		    	std::string symbol = files[i].substr(0, files[i].size() - 4);
		    	std::cout << "symbol: " << symbol << "\n";
		    	
			std::vector<Track> tracks;
			TrackLoader::load((baseDirDefault + files[i]).c_str(), tracks);
			for (size_t j = 0; j < models.size(); j++) {
				std::cout << "model: " << models[j].first << " " << models[j].second.logProb(obs) << "\n";
			}
		}
	}
	

	return 0;
}
